package com.ehouse.database;

import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import com.ehouse.provider.MainContentProvider;


public class TemperatureTable {
//	// Database table
		public static final String NAME = "temperatures";
		public static final String COLUMN_ID = "_id";

		public static final String COLUMN_TEMP = "temp";
		public static final String COLUMN_LABEL_H = "label_h";
		public static final String COLUMN_STATE_H = "state_h";
		public static final String COLUMN_LABEL_A = "label_a";
		public static final String COLUMN_STATE_A = "state_a";

		public static final Uri CONTENT_URI = Uri.parse(MainContentProvider.BASE_URI.toString() + NAME);
		
		// Database creation SQL statement
		public static final String DATABASE_CREATE = "create table " 
				+ NAME
				+ "(" + COLUMN_ID + " integer primary key autoincrement, " 
				+ COLUMN_TEMP + " real not null, " 
				+ COLUMN_LABEL_H + " text not null, " 
				+ COLUMN_STATE_H + " integer not null, " 
				+ COLUMN_LABEL_A + " text not null, " 
				+ COLUMN_STATE_A + " integer not null " + ");";
		
		@SuppressLint("DefaultLocale")
		public static void update(ContentResolver cr, HashMap<String, String> items){
		    	String[] projection = new String[]{TemperatureTable.COLUMN_ID, TemperatureTable.COLUMN_TEMP,
		    			TemperatureTable.COLUMN_LABEL_H, TemperatureTable.COLUMN_STATE_H,
		    				TemperatureTable.COLUMN_LABEL_A, TemperatureTable.COLUMN_STATE_A};
			  Cursor query = cr.query(TemperatureTable.CONTENT_URI, projection, null, null, null);

	  	      ContentValues values = new ContentValues();
	   	      values.put(TemperatureTable.COLUMN_TEMP, Double.parseDouble(items.get("VALUE")));
	   	      items.remove("VALUE");
	   	      Set<Entry<String, String>> set = items.entrySet();
	   	      for (Entry<String, String> entry : set) {
	   	    	  if (entry.getKey().toLowerCase().contains("heat")) {
			   	      values.put(TemperatureTable.COLUMN_LABEL_H, entry.getKey());
			   	      values.put(TemperatureTable.COLUMN_STATE_H, Boolean.parseBoolean(entry.getValue()) ? 1 : 0);
	   	    	  } else {
				      values.put(TemperatureTable.COLUMN_LABEL_A, entry.getKey());
			   	      values.put(TemperatureTable.COLUMN_STATE_A, Boolean.parseBoolean(entry.getValue()) ? 1 : 0);
	   	    	  }
	   	      }
	   	      
		   	   if(query.getCount() ==0)
		   	      cr.insert(TemperatureTable.CONTENT_URI, values);
		   	   else{
		   		   cr.update(TemperatureTable.CONTENT_URI, values, null, null);
		   	   }
		   	query.close();
		    
		}
}
